from rest_framework.views import APIView
from django.http import Http404
from django.http import HttpResponse
import json
from datetime import datetime
from decimal import Decimal


def get_request_data_id(request, key='id', default=None):
    """
        根据请求的内容类型解析请求数据，并返回指定键的值。
        :param request: Django的HttpRequest对象
        :param key: 要从请求数据中获取的键名
        :param default: 如果键不存在时返回的默认值
        :return: 键对应的值或默认值
        """
    if request.content_type == 'application/json':
        try:
            data = json.loads(request.body)
            return data.get(key, default)  # 使用default参数作为get方法的第二个参数
        except json.JSONDecodeError:
            return default  # 在解析JSON失败时返回默认值
    else:
        # 对于非JSON请求，假设是表单数据
        return request.POST.get(key, default)


class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        elif isinstance(obj, Decimal):
            return str(obj)
        return super().default(obj)


class MsgView(APIView):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 定义公共方法
        self.msg = self.msg
        self.success = self.success
        self.warn = self.warn
        self.error = self.error

    def msg(self, code, msg, data=None):
        resl = {}
        if data is None:
            resl = {'code': code, 'msg': msg}
        else:
            resl = {'code': code, 'msg': msg, 'data': data}
        return HttpResponse(json.dumps(resl, cls=CustomJSONEncoder), content_type='application/json; charset=utf-8')

    def success(self, data=None, msg='查询成功'):
        return self.msg(code=200, msg=msg, data=data)

    def warn(self, msg='操作异常，请重试'):
        return self.msg(code=401, msg=msg, data=None)

    def error(self, msg='系统异常'):
        return self.msg(code=501, msg=msg, data=None)


class BasedAPIView(APIView):
    def msg(self, code, msg, total=None, data=None):
        resl = {}
        if data is None:
            resl = {'code': code, 'msg': msg}
        else:
            resl = {'code': code, 'msg': msg, 'total': total, 'data': data}
        return HttpResponse(json.dumps(resl, cls=CustomJSONEncoder), content_type='application/json; charset=utf-8')

    def success(self, total=None, data=None, msg='查询成功'):
        return self.msg(code=200, msg=msg, total=total, data=data)

    def warn(self, msg='操作异常，请重试'):
        return self.msg(code=401, msg=msg, data=None)

    def error(self, msg='系统异常'):
        return self.msg(code=501, msg=msg, data=None)

    def get(self, request, *args, **kwargs):
        module = kwargs.get('module')
        if module == 'get_page_all':
            return self.get_page_all(request)
        elif module == 'getHomeChatAll':
            return self.getHomeChatAll(request)
        elif module == 'get_by_id':
            return self.get_by_id(request)
        elif module == 'get_total':
            return self.get_total(request)
        elif module == 'get_types':
            return self.get_types(request)
        else:
            return HttpResponse("error: 不支持的get请求")

    def post(self, request, *args, **kwargs):
        module = kwargs.get('module')
        if module == 'add':
            return self.add_info(request)
        elif module == 'edit':
            return self.edit_info(request)
        elif module == 'delete':
            return self.del_info(request)
        elif module == 'shell_script':
            return self.shell_script(request)
        # elif module == 'export_total':
        #     return self.export_total(request)
        else:
            return HttpResponse("error: 不支持的post请求")

    def get_page_all(self, request):
        raise NotImplementedError

    def getHomeChatAll(self, request):
        raise NotImplementedError

    def get_by_id(self, request):
        raise NotImplementedError

    def get_total(self, request):
        raise NotImplementedError

    def add_info(self, request):
        raise NotImplementedError

    def edit_info(self, request):
        raise NotImplementedError

    def del_info(self, request):
        raise NotImplementedError

    def shell_script(self, request):
        pass

    def get_types(self, request):
        pass

    # def export_total(self, request):
    #     pass
